﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Xml.Serialization;
using System.Xml;
using System.IO;
using System.Runtime.Serialization;

namespace Avanade.ViddlerDotNet
{
    public class ViddlerResponse
    {
        private MemoryStream responseStream;
        private string messageType;

        public ViddlerResponse(Stream response)
        {
            this.responseStream = new MemoryStream();
            CopyStream(response, this.responseStream);

            // Peek in the stream to determine the message type
            XmlTextReader xmlReader = new XmlTextReader(responseStream);
            while (xmlReader.Read())
            {
                if (xmlReader.NodeType == XmlNodeType.Element)
                {   
                    messageType = xmlReader.LocalName;
                    break;
                }
            }

            // Rewind the stream to the original position
            responseStream.Position = 0;
        }

        public string MessageType
        {
            get
            {
                return messageType;
            }
        }

        public int GetResponseAsInteger()
        {
            return Convert.ToInt32(GetResponseAsString());
        }

        public string GetResponseAsString()
        {
            XmlDocument document = new XmlDocument();
            document.Load(this.responseStream);
            return document.DocumentElement.InnerText;
        }

        public T GetResponseObject<T>()
        {
            try
            {
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                return (T)serializer.Deserialize(responseStream);
            }
            catch (Exception ex)
            {
                throw new ViddlerSerializationException(ex, responseStream);
            }
        }

        private void CopyStream(Stream sourceStream, Stream targetStream)
        {
            // Copy bytes from the source stream to the target stream
            byte[] buffer = new byte[1024];
            int count = 0;
            do
            {
                count = sourceStream.Read(buffer, 0, buffer.Length);
                targetStream.Write(buffer, 0, count);

            } while (count > 0);

            // Reset the cursor in the target stream
            targetStream.Position = 0;
        }
    }
}
